package mtons.cast.modules.play;

import mtons.cast.modules.data.Standing;
import mtons.cast.modules.log.Printer;
import mtons.cast.modules.play.maker.Maker;
import mtons.cast.modules.play.ticket.Ticket;
import mtons.cast.modules.utils.NumberUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 工作线程
 *
 * Created by langhsu on 2017/10/12.
 */
public class WorkTask extends TimerTask {
//    private static String TEMPLATE = "[\"37|1|112345|1|110|5|10|,,,,%s\"]"; // 5角
    private static String TEMPLATE = "[\"37|1|112345|1|110|5|100|,,,,%s\"]";  //5分

    private Maker maker;
    private Ticket ticket;
    private Double balance = 0D;

    private Standing standings = new Standing();

    public WorkTask(Maker maker, Ticket ticket) {
        this.maker = maker;
        this.ticket = ticket;
    }

    @Override
    public void run() {
        // 获取最新余额
        Double _balance = maker.balance();

        // 和上次余额对比, 判断胜负
        boolean win = true;

        if (balance > 0D) {
            win = _balance > balance;
            Printer.info("命中:" + win + ", 毛利 : " + NumberUtils.format(_balance - balance));

            if (win) {
                standings.incrementWin();
            }
        }

        String[] countdown = maker.getCountdown();

        String bill = ticket.produce(win, countdown[0]);

        if (StringUtils.isEmpty(bill)) {
            Printer.info("Not found bill! continue.");
            Printer.info("----------------");
            return;
        }

        String adv = maker.getAdv();
        maker.doBet(countdown[1], String.format(TEMPLATE, bill), adv);

        standings.incrementCount();

        // 获取下单后的余额
        balance = maker.balance();

        Printer.info("余额：" + balance + "," + standings.toString());
        Printer.info("----------------");
    }
}
